import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    meta: { title: '首页', requiresAuth: true }
  },
  {
    path: '/campaigns',
    name: 'Campaigns',
    component: () => import('@/views/Campaigns.vue'),
    meta: { title: '众筹列表', requiresAuth: true }
  },
  {
    path: '/campaign/:id',
    name: 'CampaignDetail',
    component: () => import('@/views/CampaignDetail.vue'),
    meta: { title: '众筹详情', requiresAuth: true }
  },
  {
    path: '/create',
    name: 'CreateCampaign',
    component: () => import('@/views/CreateCampaign.vue'),
    meta: { title: '创建众筹', requiresAuth: true }
  },
  {
    path: '/my-campaigns',
    name: 'MyCampaigns',
    component: () => import('@/views/MyCampaigns.vue'),
    meta: { title: '我的众筹', requiresAuth: true }
  },
  {
    path: '/debug',
    name: 'Debug',
    component: () => import('@/views/Debug.vue'),
    meta: { title: '诊断工具', requiresAuth: false }
  }
];

const router = new VueRouter({
  mode: 'hash',
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 众筹平台`;
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    let user = null;
    try {
      const userStr = localStorage.getItem('user');
      // 确保userStr不是null、undefined或字符串'undefined'
      if (userStr && userStr !== 'undefined') {
        user = JSON.parse(userStr);
      }
    } catch (e) {
      console.error('解析用户信息失败:', e);
    }
    if (!user || !user.id) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;

